<template>
  <div>
    <a-card>
      <a-table
        :row-key="(record) => record.id"
        :columns="columns"
        :data-source="rolesList"
        :pagination="pagination"
        expandRowByClick
        @change="handleTableChange"
        childrenColumnName="1"
        bordered
      >
        <!-- 渲染一级权限 -->
        <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
          <a-row
            :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'vcenter']"
            v-for="(item1, i1) in record.children"
            :key="item1.id"
          >
            <a-col :span="5">
              <a-tag color="green">{{ item1.authName }}</a-tag>
            </a-col>
            <!-- 渲染二和三级权限 -->
            <a-col :span="19">
              <!-- 通过 for 嵌套 渲染二级权限 -->
              <a-row
                v-for="(item2, i2) in item1.children"
                :key="item2.id"
                :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
              >
                <a-col :span="6">
                  <a-tag color="blue">
                    {{ item2.authName }}
                  </a-tag>
                  <i class="el-icon-caret-right"></i>
                </a-col>
                <a-col :span="18">
                  <a-tag
                    color="pink"
                    :class="[i3 === 0 ? '' : 'bdtop']"
                    v-for="(item3, i3) in item2.children"
                    :key="item3.id"
                  >
                    {{ item3.authName }}
                  </a-tag>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </p>
        <!-- <a-table
          slot="expandedRowRender"
          slot-scope="record"
          expandRowByClick
          :columns="innerColumns"
          :data-source="record.children"
          :pagination="false"
        >
        </a-table> -->
        <span slot="action" slot-scope="record">
          <a-button type="primary" @click="delRoles(record)" class="del"
            >删除</a-button
          >
          <a-button type="primary" @click="showModal(record)">
            分配权限
          </a-button>
        </span>
      </a-table>

      <a-modal
        title="分配权限"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-tree checkable :tree-data="treeData" :replace-fields="replaceFields" :default-checked-keys="defKeys" ref="treeRef" >
        </a-tree>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { getRolesList, delRolesList,setRights } from "@/network/Role";
import { getRightList } from "@/network/rights";
export default {
  components: {},
  data() {
    return {
      // innerColumns: [
      //   {
      //     title: "权限名称",
      //     dataIndex: "authName",
      //     align: "center",
      //   },
      //   { title: "路径", dataIndex: "path", align: "center" },
      // ],
      rolesList: [],
      treeData: [],
      rolesId:'',
      visible: false,
      confirmLoading: false,
      replaceFields: {
        children: "children",
        title: "authName",
        key:'id'
      },
      // 树形控件 -> 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色的ID
      rolesId: "",
      pagination: {
        total: 0,
        current: 1,
        pageSize: 5,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "15", "20", "25"],
      },
      columns: [
        {
          title: "序号",
          customRender: (text, record, index) => {
            return (
              this.pagination.pageSize * (this.pagination.current - 1) +
              index +
              1
            );
          },
          align: "center",
        },
        {
          title: "角色名称",
          dataIndex: "roleName",
          align: "center",
        },
        {
          title: "角色描述",
          dataIndex: "roleDesc",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    handleTableChange(pagination) {
      this.pagination = pagination;
      this.getRolesList();
    },
    getRolesList() {
      getRolesList().then((res) => {
        this.rolesList = res.data;
      });
    },
    delRoles(record) {
      const _this = this;
      this.$confirm({
        title: "你确定要删除吗?",
        content: `${record.roleDesc}`,
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          delRolesList(record.id).then(
            (res) => {
              _this.$message.success("删除成功");
              _this.getRolesList();
            },
            (err) => {
              console.log(err);
            }
          );
        },
        onCancel() {
          _this.$message.info("取消删除");
        },
      });
    },
    showModal(roles) {
      this.visible = true;
      getRightList('tree').then((res) => {
        this.treeData = res.data;
        // 递归获取三级节点
        this.getLeafKeys(roles, this.defKeys);
        this.visible = true;
      });
    },
    // 递归的形式,获取角色下所有的三级权限的id,并保存到 defKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前node没有children属性则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    handleOk() {
      const keys = [...this.$refs.treeRef.setCheckedKeys(), ...this.$refs.treeRef.setHalfCheckedKeys()]
      const idStr = keys.join(',')
      const params={
        rids:idStr
      }
      setRights(this.rolesId,params).then(
        res =>{
          if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.visible = false
        }
      )
    },
    handleCancel() {
      this.visible = false;
    },
    //获取所有的权限列表
  },
};
</script>

<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
.del {
  margin-right: 10px;
}
</style>